﻿#include "mythread.h"
#include <QElapsedTimer>
#include <QDebug>

MyGenerate::MyGenerate(QObject *parent)	: QThread(parent)
{}

MyGenerate::~MyGenerate()
{}

void MyGenerate::RecvNum(int num)
{
    m_num = num;
}

void MyGenerate::run()
{
    QElapsedTimer time;
    time.start();
    qDebug() << "Generate qrand Address QThreadID:" << QThread::currentThread();
    QVector<int> list;
    for (int i = 0; i < m_num; ++i)
    {
        list.push_back(qrand() % 100000);
    }
    int milsec = time.elapsed();
    qDebug() << "Generate Number:" << m_num << " Time:" << milsec << "millisecond";
    emit sendArray(list);
}

MyQuickSort::MyQuickSort(QObject* parent)
{
}

MyQuickSort::~MyQuickSort()
{
}

void MyQuickSort::RecvArray(QVector<int> list)
{
    m_list = list;
}

void MyQuickSort::run()
{
    QElapsedTimer time;
    time.start();
    qDebug() << "QuickSort Address threadID:" << QThread::currentThread();
    quickSort(m_list,0,m_list.size() -1);
    int milsec = time.elapsed();
    qDebug() << "QuickSort Times:" << milsec << "millisecond";
    emit finish(m_list);
}

void MyQuickSort::quickSort(QVector<int>& list, int l, int r)
{
    if (l < r)
    {
        int i = l, j = r;
        //拿出第一个元素，保存到x中， 第一个位置成为一个坑
        int x = list[l];
        while (i < j)
        {
            //从右向左找最小的x的数
            while (i < j && list[j] >= x)
            {
                //左移，直到遇到小于等于x的数
                j--;
            }
            if (i < j)
            {
                //将右侧找到的小于x的元素放入左侧的坑中，右侧出现一个坑，左侧元素索引后移
                list[i++] = list[j];
            }
            while (i < j && list[i] < x)
            {
                //右移，知道遇到大于x的数
                i++;
            }
            if ( i < j)
            {
                //将左侧找到的元素放到右侧坑中，左侧出现一个坑，右侧元素索引向前移动
                list[j--] = list[i];
            }
        }
        //此时 i = j，将保存在x中的数填入坑中
        list[i] = x;
        quickSort(list,l,i - 1);
        quickSort(list,i + 1, r);
    }
}

MyBubbleSort::MyBubbleSort(QObject* parent)
{
}

MyBubbleSort::~MyBubbleSort()
{
}

void MyBubbleSort::RecvArray(QVector<int> list)
{
    m_list = list;
}

void MyBubbleSort::run()
{
    QElapsedTimer time;
    time.start();
    qDebug() << "BubbleSort Address threadID:" << QThread::currentThread();
    bubbleSort(m_list,0,m_list.size() -1);
    int milsec = time.elapsed();
    qDebug() << "BubbleSort Times:" << milsec << "millisecond";
    emit finish(m_list);
}

void MyBubbleSort::bubbleSort(QVector<int> &list, int l, int r)
{
    for (int i = 0; i < list.size(); ++i)
    {
        for (int j = 0; j < list.size() - i - 1; ++j)
        {
            if (list[j] > list[j + 1])
            {
                auto temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }
}
